package com.bbx.hive.udf.udtf;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;
import java.util.List;

public class MyUdtf extends GenericUDTF {

    private List outList = new ArrayList();

    /**
     * 定时输数数据的列名和输出数据类型
     * @param argOIs
     * @return
     * @throws UDFArgumentException
     */
    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
        //返回列名
         List<String> fieldNames = new ArrayList<>();
         fieldNames.add("myUDTFFieldName");
         //返回数据类型
        List<ObjectInspector> fieldOIs = new ArrayList<>();
        fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs);
    }

    @Override
    public void process(Object[] args) throws HiveException {
        //获取原始数据
        String data = args[0].toString();
        //获取分割器
        String keySplit = args[1].toString();
        //分割数据
        String[] split = data.split(keySplit);
       for(String str:split){
           //为什么需要outList---->输出的列名(fieldNames),类型(fieldOIs)为list,需要对应
            outList.clear();
            outList.add(str);
            //写出数据
            forward(outList);
        };

    }

    @Override
    public void close() throws HiveException {

    }
}
